//
//  YDKeyboardViewController.m
//  IngCard
//
//  Created by kf on 2017/6/8.
//  Copyright © 2017年 IngDan. All rights reserved.
//

#import "YDTextFieldKeyboardViewController.h"

static CGFloat const kToolbarHeight = 50;

@interface YDTextFieldKeyboardViewController ()<QMUIKeyboardManagerDelegate,QMUITextFieldDelegate>
@property(nonatomic, strong) QMUIKeyboardManager *keyboardManager;

@property(nonatomic, strong) UIControl *maskControl;
@property(nonatomic, strong) QMUITextField *textField;

@property(nonatomic, strong) UIView *toolbarView;

@property(nonatomic, copy) void (^onComplete)(NSString *);
@property(nonatomic, copy) void (^onCancel)(void);
@property(nonatomic, assign) BOOL beCancel;
@end

@implementation YDTextFieldKeyboardViewController

- (void)initSubviews {
    [super initSubviews];
    
    [self.keyboardManager addTargetResponder:self.textField];
    
    self.view.backgroundColor = UIColorClear;
    
    self.maskControl.frame = self.view.bounds;
    [self.view addSubview:self.maskControl];
    
    self.toolbarView.frame = CGRectFlatMake(0, CGRectGetHeight(self.view.bounds),
                                            CGRectGetWidth(self.view.bounds), kToolbarHeight);
    [self.view addSubview:self.toolbarView];
    
    self.textField.frame = CGRectFlatMake(0,0,
                                          CGRectGetWidth(self.toolbarView.bounds),
                                          kToolbarHeight);
    [self.toolbarView addSubview:self.textField];
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

#pragma mark - public
- (BOOL)isShowing
{
    if (self.parendViewController &&
        self.view.superview)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)showWithPlaceholder:(NSString *)placeholder
                 onComplete:(void (^)(NSString *)) onComplete
                   onCancel:(void (^)())onCancel
{
    // 这一句访问了self.view，触发viewDidLoad:
    
    if (self.parendViewController && ![self isShowing])
    {
        self.view.frame = self.parendViewController.view.bounds;
        [self.parendViewController.view addSubview:self.view];
        [self.view layoutIfNeeded];
        
        self.maskControl.alpha = 0.0;
        [UIView animateWithDuration:0.25 delay:0.0 options:QMUIViewAnimationOptionsCurveOut animations:^{
            self.maskControl.alpha = 1.0;
        }completion:^(BOOL finished){}];
        
        self.textField.text = placeholder;
        [self.textField becomeFirstResponder];
        self.onComplete = onComplete;
        self.onCancel = onCancel;
        self.beCancel = NO;
    }
}

- (void)hide
{
    __weak __typeof(self)weakSelf = self;
    
    [self.textField resignFirstResponder];
    !self.beCancel ? self.onComplete(self.textField.text) : self.onCancel();
    
    self.onCancel = nil;
    self.onComplete = nil;
    self.textField.text = nil;
    self.textField.placeholder = @"请输入...";
    
    
    [UIView animateWithDuration:.25 delay:0.0 options:QMUIViewAnimationOptionsCurveOut animations:^
    {
        __strong __typeof(weakSelf)self = weakSelf;
        self.maskControl.alpha = 0.0;
    } completion:^(BOOL finished)
    {
        __strong __typeof(weakSelf)self = weakSelf;
        [self.view removeFromSuperview];
    }];
}

#pragma mark - <QMUIKeyboardManagerDelegate,UITextFieldDelegate>

- (void)keyboardWillChangeFrameWithUserInfo:(QMUIKeyboardUserInfo *)keyboardUserInfo {
    __weak __typeof(self)weakSelf = self;
    [QMUIKeyboardManager handleKeyboardNotificationWithUserInfo:keyboardUserInfo
                                                      showBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo)
     {
         [QMUIKeyboardManager animateWithAnimated:NO
                                 keyboardUserInfo:keyboardUserInfo
                                       animations:^
          {
              __strong __typeof(weakSelf)self = weakSelf;
              CGFloat distanceFromBottom = [QMUIKeyboardManager distanceFromMinYToBottomInView:weakSelf.view
                                                                                  keyboardRect:keyboardUserInfo.endFrame];
              
              CGFloat pointY = CGRectGetHeight(self.view.bounds) - distanceFromBottom - kToolbarHeight;
              self.toolbarView.frame = CGRectMake(0,pointY, CGRectGetWidth(self.view.bounds), kToolbarHeight);
              
          } completion:NULL];
     } hideBlock:^(QMUIKeyboardUserInfo *keyboardUserInfo)
     {
         __strong __typeof(weakSelf)self = weakSelf;
         [self hide];
         
         self.toolbarView.frame =  CGRectMake(0, CGRectGetHeight(self.view.bounds),
                                              CGRectGetWidth(self.view.bounds), kToolbarHeight);
         
     }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.textField resignFirstResponder];
    return YES;
}

#pragma mark - private

- (void)handleCompleteButtonEvent:(id)sender
{
     [self.textField resignFirstResponder];
}

- (void)handleCancelButtonEvent:(id)sender
{
    self.beCancel = YES;
    [self.textField resignFirstResponder];
}

#pragma mark - lazy load
-(UIControl *)maskControl
{
    if (!_maskControl)
    {
        _maskControl = [[UIControl alloc] init];
        _maskControl.backgroundColor = UIColorMask;
        [_maskControl addTarget:self action:@selector(handleCancelButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _maskControl;
}

-(QMUITextField *)textField
{
    if (!_textField)
    {
        _textField = [[QMUITextField alloc] init];;
        _textField.delegate = self;
        _textField.placeholder = @"请输入...";
        _textField.font = UIFontMake(14);
        _textField.textInsets = UIEdgeInsetsMake(8, 8, 8, 8);
        _textField.returnKeyType = UIReturnKeyDone;
        _textField.backgroundColor = UIColorWhite;
    }
    return _textField;
}

-(UIView *)toolbarView
{
    if (!_toolbarView)
    {
        _toolbarView = [[UIView alloc] init];
        _toolbarView.backgroundColor = UIColorForBackground;
        _toolbarView.qmui_borderColor = UIColorSeparator;
        _toolbarView.qmui_borderPosition = QMUIBorderViewPositionTop;
    }
    return _toolbarView;
}

-(QMUIKeyboardManager *)keyboardManager
{
    if (!_keyboardManager)
    {
        _keyboardManager = [[QMUIKeyboardManager alloc] initWithDelegate:self];
    }
    return _keyboardManager;
}
@end
